<template>
  <div class="calendar-view-content">
    <div class="calendar-header">
      <button @click="previousMonth" class="nav-button">&#xE72B;</button>
      <h2>{{ currentMonthFormatted }}</h2>
      <button @click="nextMonth" class="nav-button">&#xE72A;</button>
      <button @click="goToTodayInCalendar" class="today-button">回到今日</button>
    </div>

    <div class="add-todo-for-date-section" v-if="calendarSelectedKey">
        <input
          type="text"
          class="todo-input-for-date"
          placeholder="为选中日期添加待办..."
          v-model="newTodoForSelectedDateText"
          @keyup.enter="handleAddTodoToSelectedDate"
        >
        <button @click="handleAddTodoToSelectedDate" class="add-button-for-date">添加</button>
    </div>

    <div class="calendar-main-area">
      <div class="calendar-grid-container">
        <div class="calendar-weekdays">
          <div v-for="day in weekdays" :key="day" class="weekday">{{ day }}</div>
        </div>
        <div class="calendar-days">
          <div v-for="(blank, index) in leadingBlankDays" :key="`blank-leading-${index}`" class="day-cell blank"></div>
          <div
            v-for="day in daysInMonth"
            :key="day.dateKey"
            :class="['day-cell', {
              'today': day.isToday,
              'selected': day.dateKey === calendarSelectedKey,
              'has-todos': day.todoCount > 0
            }]"
            @click="handleDayCellClick(day.date)"
          >
            <span class="day-number">{{ day.dayNumber }}</span>
            <span v-if="day.todoCount > 0" class="todo-indicator"></span>
          </div>
        </div>
      </div>

      <div class="selected-day-panel">
        <div class="batch-controls-bar-calendar-panel" v-if="calendarSelectedKey && todosForCalendarSelectedDate.length > 0">
          <input
            type="checkbox"
            :checked="isAllSelectedInCalendarPanel && todosForCalendarSelectedDate.length > 0"
            @change="toggleSelectAllInCalendarPanel"
            :id="'select-all-todos-calendar-panel-' + calendarSelectedKey"
            title="全选/取消全选"
            class="select-all-checkbox-calendar-panel"
          >
          <label :for="'select-all-todos-calendar-panel-' + calendarSelectedKey" class="select-all-label-calendar-panel">全选</label>
          <button @click="handleBatchDeleteForCalendarPanel" :disabled="!hasSelectedTodosInCalendarPanel" class="batch-action-button delete">
            <span class="button-icon">&#xE74D;</span> 删除选中
          </button>
          <button @click="handleBatchArchiveForCalendarPanel" :disabled="!hasSelectedTodosInCalendarPanel" class="batch-action-button archive">
            <span class="button-icon">&#xE7B8;</span> 归档选中
          </button>
        </div>

        <div class="selected-day-todos-list" v-if="calendarSelectedKey && todosForCalendarSelectedDate.length > 0">
          <ul class="todo-list">
            <li
              v-for="todo in todosForCalendarSelectedDate"
              :key="todo.id"
              :class="['todo-item', { 'completed': todo.completed, 'selected-for-batch': selectedTodoIdsForCalendarPanel.includes(todo.id) }]"
              @contextmenu.prevent="openCalendarPanelContextMenu(todo, $event)"
            >
              <input
                type="checkbox"
                :id="'select-cal-todo-' + todo.id"
                class="todo-select-checkbox-calendar-panel"
                :checked="selectedTodoIdsForCalendarPanel.includes(todo.id)"
                @change="toggleTodoSelectionInCalendarPanel(todo.id)"
              >
              <span
                @click="handleToggleTodo(todo.id)"
                :class="['todo-status-icon', todo.completed ? 'completed-icon' : 'pending-icon']"
                :title="todo.completed ? '标记为未完成' : '标记为已完成'"
              >
                 {{ todo.completed ? '&#xE930;' : '&#xE931;' }}
              </span>
              <span
                class="priority-indicator"
                :style="{ backgroundColor: getPriorityColor(todo.priority) }"
                :title="'优先级: ' + getPriorityText(todo.priority)"
              ></span>
              <label
                v-if="editingTodoId !== todo.id"
                class="todo-label"
                @dblclick="startEditing(todo)"
                :title="todo.text"
              >
                {{ todo.text }}
              </label>
              <input
                v-else
                type="text"
                v-model="editingTodoText"
                class="todo-edit-input"
                @blur="saveEdit(todo.id)"
                @keyup.enter="saveEdit(todo.id)"
                @keyup.esc="cancelEdit"
                v-focus
              />
            </li>
          </ul>
        </div>
        <p v-else-if="calendarSelectedKey" class="empty-selected-day-message">选定日期没有待办事项。 <br>您可以通过上方输入框添加新的待办。</p>
        <p v-else class="empty-selected-day-message">请在左侧日历中选择一个日期。</p>
      </div>

    </div>
    
    <div class="calendar-footer">
      <div class="priority-legend-container">
          <div class="priority-legend">
            <!-- <span class="legend-title">图例:</span> -->
            <div class="legend-item">
              <span class="legend-dot" :style="{ backgroundColor: getPriorityColor(PRIORITIES.HIGH) }"></span>
              <span>{{ getPriorityText(PRIORITIES.HIGH) }}</span>
            </div>
            <div class="legend-item">
              <span class="legend-dot" :style="{ backgroundColor: getPriorityColor(PRIORITIES.MEDIUM) }"></span>
              <span>{{ getPriorityText(PRIORITIES.MEDIUM) }}</span>
            </div>
            <div class="legend-item">
              <span class="legend-dot" :style="{ backgroundColor: getPriorityColor(PRIORITIES.LOW) }"></span>
              <span>{{ getPriorityText(PRIORITIES.LOW) }}</span>
            </div>
            <div class="legend-item">
              <span class="legend-dot" :style="{ backgroundColor: getPriorityColor(PRIORITIES.NONE) }"></span>
              <span>{{ getPriorityText(PRIORITIES.NONE) }}</span>
            </div>
          </div>
        </div>
    </div>

    <!-- Context Menu for Calendar Panel Todos -->
    <div 
      v-if="calendarPanelContextMenu.visible"
      ref="calendarPanelContextMenuRef"
      class="context-menu"
      :style="{ top: calendarPanelContextMenu.top + 'px', left: calendarPanelContextMenu.left + 'px' }"
      @click.stop
      v-click-outside="closeCalendarPanelContextMenu"
    >
      <div 
        class="context-menu-item priority-submenu-container"
        ref="prioritySubmenuParentRef"
        @mouseenter="openPrioritySubmenu"
        @mouseleave="scheduleClosePrioritySubmenu"
      >
        <span>设置优先级</span>
        <span class="submenu-arrow">&#xE76C;</span>
      </div>
      <div class="context-menu-item" @click="editCalendarPanelContextTodo">编辑</div>
      <div class="context-menu-item" @click="archiveCalendarPanelContextTodo">归档</div>
      <div class="context-menu-item" @click="deleteCalendarPanelContextTodo">删除</div>
      <div class="context-menu-item" @click="openCalendarPanelDatePickerContextTodo">修改日期</div>
    </div>

    <!-- Priority Submenu for CalendarView -->
    <div
      v-if="prioritySubmenu.visible"
      ref="prioritySubmenuRef"
      class="priority-submenu" 
      :class="{ 'submenu-positioned-left': prioritySubmenu.isPositionedLeft }"
      :style="prioritySubmenu.style"
      @mouseenter="clearClosePrioritySubmenuTimer"
      @mouseleave="scheduleClosePrioritySubmenu(true)"
      @click.stop
    >
      <div class="context-menu-item" @click="setCalendarPanelContextMenuTodoPriority(PRIORITIES.HIGH)">
        <span class="priority-dot" :style="{ backgroundColor: getPriorityColor(PRIORITIES.HIGH) }"></span> 高
      </div>
      <div class="context-menu-item" @click="setCalendarPanelContextMenuTodoPriority(PRIORITIES.MEDIUM)">
        <span class="priority-dot" :style="{ backgroundColor: getPriorityColor(PRIORITIES.MEDIUM) }"></span> 中
      </div>
      <div class="context-menu-item" @click="setCalendarPanelContextMenuTodoPriority(PRIORITIES.LOW)">
        <span class="priority-dot" :style="{ backgroundColor: getPriorityColor(PRIORITIES.LOW) }"></span> 低
      </div>
      <div class="context-menu-item" @click="setCalendarPanelContextMenuTodoPriority(PRIORITIES.NONE)">
        <span class="priority-dot" :style="{ backgroundColor: getPriorityColor(PRIORITIES.NONE) }"></span> {{ getPriorityText(PRIORITIES.NONE) }}
      </div>
    </div>

    <!-- Mini Calendar for Date Picking in Calendar Panel -->
    <MiniCalendar
      ref="calendarPanelMiniCalendar" 
      :targetElement="datePickerTargetElement"
      :initialDate="datePickerInitialDate"
      @date-selected="handleDateSelectedForCalendarPanelTodo"
      @close="closeCalendarPanelDatePicker"
    />
  </div>
</template>

<script>
import { mapState, mapGetters, mapActions } from 'vuex';
import { getFormattedDateKey } from '../utils/dateUtils';
import { getPriorityText, getPriorityColor, getPriorityIcon, PRIORITIES } from '../utils/priorityUtils';
import { calculateContextMenuPosition, calculateSubmenuPosition } from '../utils/contextMenuUtils';
import MiniCalendar from '../components/MiniCalendar.vue';
import Vue from 'vue';

export default {
  name: 'CalendarView',
  components: {
    MiniCalendar
  },
  data() {
    return {
      viewDate: new Date(),
      weekdays: ['日', '一', '二', '三', '四', '五', '六'],
      editingTodoId: null,
      editingTodoText: '',
      newTodoForSelectedDateText: '',
      locallySelectedDate: null,
      selectedTodoIdsForCalendarPanel: [],
      calendarPanelContextMenu: {
        visible: false,
        top: 0,
        left: 0,
        selectedTodo: null,
        dimensions: { width: 160, height: 160 },
        isPushedLeft: false
      },
      prioritySubmenu: {
        visible: false,
        style: {},
        isPositionedLeft: false,
        dimensions: { width: 100, height: 130 },
        closeTimer: null
      },
      PRIORITIES: PRIORITIES,
      datePickerTargetTodoId: null,
      datePickerTargetElement: null,
      datePickerInitialDate: new Date(),
    };
  },
  computed: {
    ...mapState(['currentDate', 'todosByDate']),
    ...mapGetters(['formattedCurrentDateKey', 'isDataReady']),
    currentMonthFormatted() {
      return this.viewDate.toLocaleDateString('zh-CN', { year: 'numeric', month: 'long' });
    },
    daysInMonth() {
      const year = this.viewDate.getFullYear();
      const month = this.viewDate.getMonth();
      const daysArray = [];
      const todayKey = getFormattedDateKey(new Date());
      const numDays = new Date(year, month + 1, 0).getDate();

      for (let i = 1; i <= numDays; i++) {
        const date = new Date(year, month, i);
        const dateKey = getFormattedDateKey(date);
        const todosForThisDay = this.todosByDate[dateKey] || [];
        const todoCount = todosForThisDay.length;
        
        daysArray.push({
          date,
          dateKey,
          dayNumber: i,
          isToday: dateKey === todayKey,
          todoCount: todoCount
        });
      }
      return daysArray;
    },
    leadingBlankDays() {
      const year = this.viewDate.getFullYear();
      const month = this.viewDate.getMonth();
      const firstDayOfMonthWeekday = new Date(year, month, 1).getDay();
      return Array(firstDayOfMonthWeekday).fill(null);
    },
    calendarSelectedDateObject() {
      return this.locallySelectedDate;
    },
    calendarSelectedKey() {
      return this.locallySelectedDate ? getFormattedDateKey(this.locallySelectedDate) : null;
    },
    calendarSelectedDateFormatted() {
      if (!this.locallySelectedDate) return '';
      return this.locallySelectedDate.toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric', weekday: 'long' });
    },
    todosForCalendarSelectedDate() {
      if (!this.calendarSelectedKey || !this.todosByDate[this.calendarSelectedKey]) {
        return [];
      }
      return [...this.todosByDate[this.calendarSelectedKey]];
    },
    isAllSelectedInCalendarPanel() {
      if (this.todosForCalendarSelectedDate.length === 0) return false;
      return this.selectedTodoIdsForCalendarPanel.length === this.todosForCalendarSelectedDate.length;
    },
    hasSelectedTodosInCalendarPanel() {
      return this.selectedTodoIdsForCalendarPanel.length > 0;
    },
    getFormattedDateKey() {
      return getFormattedDateKey;
    }
  },
  methods: {
    ...mapActions([
      'selectDate',
      'goToToday',
      'addTodoToDate',
      'toggleTodo',
      'updateTodoText',
      'deleteTodo',
      'deleteBatchTodosFromDate', 
      'updateTodoPriority',
      'updateTodoTextForDate',
      'deleteTodoFromDate',
      'updateTodoPriorityForDate',
      'moveTodoToDate',
      'addTodo',
      'archiveTodo',
      'archiveBatchTodos',
      'setSelectedDate',
      'fetchTodosForDate'
    ]),
    getPriorityText,
    getPriorityColor,
    getPriorityIcon,
    previousMonth() {
      const newDate = new Date(this.viewDate);
      newDate.setMonth(newDate.getMonth() - 1);
      this.viewDate = newDate;
    },
    nextMonth() {
      const newDate = new Date(this.viewDate);
      newDate.setMonth(newDate.getMonth() + 1);
      this.viewDate = newDate;
    },
    goToTodayInCalendar() {
      const today = new Date();
      this.viewDate = new Date(today.getFullYear(), today.getMonth(), 1);
      this.locallySelectedDate = today;
      this.goToToday(); 
    },
    handleDayCellClick(date) { 
      this.locallySelectedDate = date;
      this.selectedTodoIdsForCalendarPanel = [];
    },
    handleAddTodoToSelectedDate() {
      if (this.newTodoForSelectedDateText.trim() && this.calendarSelectedKey) {
        this.addTodoToDate({ 
          text: this.newTodoForSelectedDateText.trim(), 
          date: new Date(this.locallySelectedDate)
        });
        this.newTodoForSelectedDateText = '';
      }
    },
    handleToggleTodo(todoId) {
      this.toggleTodo(todoId);
    },
    handleDeleteTodo(todoId) {
      this.deleteTodo(todoId);
    },
    startEditing(todo) {
      this.editingTodoId = todo.id;
      this.editingTodoText = todo.text;
    },
    saveEdit(todoId) {
      if (this.editingTodoId === todoId && this.editingTodoText.trim()) {
        this.updateTodoText({ todoId, newText: this.editingTodoText.trim(), dateKey: this.calendarSelectedKey });
      }
      this.cancelEdit();
    },
    cancelEdit() {
      this.editingTodoId = null;
      this.editingTodoText = '';
    },
    toggleSelectAllInCalendarPanel() {
      if (this.isAllSelectedInCalendarPanel) {
        this.selectedTodoIdsForCalendarPanel = [];
      } else {
        this.selectedTodoIdsForCalendarPanel = this.todosForCalendarSelectedDate.map(todo => todo.id);
      }
    },
    toggleTodoSelectionInCalendarPanel(todoId) {
      const index = this.selectedTodoIdsForCalendarPanel.indexOf(todoId);
      if (index > -1) {
        this.selectedTodoIdsForCalendarPanel.splice(index, 1);
      } else {
        this.selectedTodoIdsForCalendarPanel.push(todoId);
      }
    },
    handleBatchDeleteForCalendarPanel() {
      if (this.selectedTodoIdsForCalendarPanel.length > 0 && this.calendarSelectedKey) {
        const todoIds = [...this.selectedTodoIdsForCalendarPanel];
        console.log('[CalendarView] 批量删除待办事项:', todoIds, '从日期:', this.calendarSelectedKey);
        this.deleteBatchTodosFromDate({ 
          todoIdsArray: todoIds, 
          dateKey: this.calendarSelectedKey 
        });
        this.selectedTodoIdsForCalendarPanel = [];
      } else {
        console.log('[CalendarView] 批量删除：未选中任何待办事项，操作已取消');
      }
    },
    handleBatchArchiveForCalendarPanel() {
      if (this.hasSelectedTodosInCalendarPanel && this.calendarSelectedKey) {
        this.archiveBatchTodos({ 
          todoIds: [...this.selectedTodoIdsForCalendarPanel], 
          source: 'date', 
          dateKeyIfFromDate: this.calendarSelectedKey 
        });
        this.selectedTodoIdsForCalendarPanel = [];
      }
    },
    openCalendarPanelContextMenu(todo, event) {
      this.calendarPanelContextMenu.selectedTodo = todo;
      const { top, left, adjustedLeft } = calculateContextMenuPosition(event, this.calendarPanelContextMenu.dimensions);
      this.calendarPanelContextMenu.top = top;
      this.calendarPanelContextMenu.left = left;
      this.calendarPanelContextMenu.isPushedLeft = adjustedLeft;
      this.calendarPanelContextMenu.visible = true;

      if (this.prioritySubmenu.visible) {
        this.prioritySubmenu.visible = false;
      }
    },
    closeCalendarPanelContextMenu() {
      if (this.calendarPanelContextMenu.visible) {
        this.calendarPanelContextMenu.visible = false;
        this.calendarPanelContextMenu.selectedTodo = null;
        if (this.prioritySubmenu.visible) {
          this.prioritySubmenu.visible = false;
        }
      }
    },
    openPrioritySubmenu() {
      if (!this.$refs.prioritySubmenuParentRef) return;
      this.clearClosePrioritySubmenuTimer();
      this.prioritySubmenu.visible = true;

      this.$nextTick(() => {
        if (!this.$refs.prioritySubmenuParentRef || !this.$refs.prioritySubmenuRef) {
          this.prioritySubmenu.visible = false;
          return;
        }
        const parentRect = this.$refs.prioritySubmenuParentRef.getBoundingClientRect();
        const submenuDimensions = this.prioritySubmenu.dimensions;
        const { top, left, positionedRight } = calculateSubmenuPosition(parentRect, submenuDimensions);
        
        this.prioritySubmenu.style = { top: `${top}px`, left: `${left}px` };
        this.prioritySubmenu.isPositionedLeft = !positionedRight;
      });
    },
    scheduleClosePrioritySubmenu(isMouseLeaveFromSubmenu = false) {
      this.clearClosePrioritySubmenuTimer();
      this.prioritySubmenu.closeTimer = setTimeout(() => {
        this.prioritySubmenu.visible = false;
      }, isMouseLeaveFromSubmenu ? 50 : 150);
    },
    clearClosePrioritySubmenuTimer() {
      if (this.prioritySubmenu.closeTimer) {
        clearTimeout(this.prioritySubmenu.closeTimer);
        this.prioritySubmenu.closeTimer = null;
      }
    },
    setCalendarPanelContextMenuTodoPriority(priority) {
      if (this.calendarPanelContextMenu.selectedTodo) {
        this.updateTodoPriority({ todoId: this.calendarPanelContextMenu.selectedTodo.id, priority, dateKey: this.calendarSelectedKey });
      }
      this.closeCalendarPanelContextMenu();
    },
    editCalendarPanelContextTodo() {
      if (this.calendarPanelContextMenu.selectedTodo) {
        this.startEditing(this.calendarPanelContextMenu.selectedTodo);
      }
      this.closeCalendarPanelContextMenu();
    },
    archiveCalendarPanelContextTodo() {
      if (this.calendarPanelContextMenu.selectedTodo && this.calendarSelectedKey) {
        this.archiveTodo({ 
          todo: this.calendarPanelContextMenu.selectedTodo, 
          originalSource: `date_${this.calendarSelectedKey}` 
        });
      }
      this.closeCalendarPanelContextMenu();
    },
    deleteCalendarPanelContextTodo() {
      if (this.calendarPanelContextMenu.selectedTodo && this.calendarPanelContextMenu.selectedTodo.id && this.calendarSelectedKey) {
        this.deleteTodo({ todoId: this.calendarPanelContextMenu.selectedTodo.id, dateKey: this.calendarSelectedKey });
      } else {
        console.warn("[CalendarView] deleteCalendarPanelContextTodo: Attempted to delete with no selected todo, no todo id, or no selected date.", { 
          selectedTodo: this.calendarPanelContextMenu.selectedTodo, 
          dateKey: this.calendarSelectedKey 
        });
      }
      this.closeCalendarPanelContextMenu();
    },
    openCalendarPanelDatePickerContextTodo() {
      if (this.calendarPanelContextMenu.selectedTodo) {
        const todo = this.calendarPanelContextMenu.selectedTodo;
        const eventTargetElement = this.$refs.calendarPanelContextMenuRef;
        this.datePickerTargetTodoId = todo.id;
        this.datePickerTargetElement = eventTargetElement;
        const todoData = (this.todosByDate[this.calendarSelectedKey] || []).find(t => t.id === todo.id);
        this.datePickerInitialDate = todoData && todoData.date ? new Date(todoData.date) : new Date(this.calendarSelectedKey || new Date()); 
        if (this.$refs.calendarPanelMiniCalendar) {
          this.$refs.calendarPanelMiniCalendar.open();
        }
      }
      this.closeCalendarPanelContextMenu();
    },
    closeCalendarPanelDatePicker() {
      this.datePickerTargetTodoId = null;
      this.datePickerTargetElement = null;
    },
    handleDateSelectedForCalendarPanelTodo(selectedDate) {
      if (this.datePickerTargetTodoId && this.calendarSelectedKey) {
        const originalDateKey = this.calendarSelectedKey;
        const todoToMove = (this.todosByDate[originalDateKey] || []).find(t => t.id === this.datePickerTargetTodoId);
        this.moveTodoToDate({ todoId: this.datePickerTargetTodoId, originalDateKey, newDate: selectedDate });
        this.datePickerTargetTodoId = null;
      }
    }
  },
  directives: {
    focus: {
      inserted: function (el) {
        el.focus();
      },
      update: function(el, binding, vnode) {
        if (vnode.key === vnode.context.editingTodoId) {
             Vue.nextTick(() => el.focus());
        }
      }
    }
  },
  watch: {
    calendarSelectedKey(newKey, oldKey) {
      if (newKey && newKey !== oldKey) {
        this.selectedTodoIdsForCalendarPanel = [];
        this.editingTodoId = null; 
        this.newTodoForSelectedDateText = '';
        console.log(`[CalendarView.vue] Watcher: calendarSelectedKey changed to ${newKey}. Fetching todos.`);
        this.fetchTodosForDate(newKey);
      }
    },
    isDataReady: {
      handler(newValue) {
        if (newValue && !this.locallySelectedDate) {
          this.locallySelectedDate = this.currentDateObject || new Date();
        }
      },
      immediate: true
    },
    currentDateObject: {
      handler(newDate) {
        if (newDate && (!this.locallySelectedDate || getFormattedDateKey(newDate) !== getFormattedDateKey(this.locallySelectedDate))) {
          this.viewDate = new Date(newDate.getFullYear(), newDate.getMonth(), 1);
          this.locallySelectedDate = newDate;
        }
      },
      immediate: true
    }
  },
  created() {
    if (!this.locallySelectedDate && this.isDataReady) {
         this.locallySelectedDate = this.currentDateObject || new Date();
         this.viewDate = new Date(this.locallySelectedDate.getFullYear(), this.locallySelectedDate.getMonth(), 1);
    } else if (!this.locallySelectedDate) {
         const today = new Date();
         this.locallySelectedDate = today;
         this.viewDate = new Date(today.getFullYear(), today.getMonth(), 1);
    }
    if (this.calendarSelectedKey) {
        console.log(`[CalendarView.vue] Created/Mounted: Initial calendarSelectedKey is ${this.calendarSelectedKey}. Fetching todos.`);
        this.fetchTodosForDate(this.calendarSelectedKey);
    } else {
        console.log("[CalendarView.vue] Created/Mounted: calendarSelectedKey not yet available for initial fetch.");
    }
  }
}
</script>

<style scoped>
/* Base Styles for Calendar View using Semantic CSS Variables */
.calendar-view-content {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: var(--theme-bg-content-area);
  color: var(--theme-text-primary);
  padding: 0; /* Remove padding if MainLayout provides it, or set to var(--spacing-base) */
  gap: 0; /* Manage gaps internally */
}

.calendar-header {
  display: flex;
  align-items: center;
  padding: var(--spacing-sm) var(--spacing-base);
  background: var(--theme-bg-titlebar);
  border-bottom: var(--border-width) var(--border-style) var(--theme-border-primary);
  flex-shrink: 0;
}

.calendar-header h2 {
  font-size: var(--font-size-xl);
  font-weight: var(--font-weight-semibold);
  color: var(--theme-text-primary);
  margin: 0 var(--spacing-base);
  text-align: center;
  flex-grow: 1;
}

.nav-button, .today-button {
  background: transparent;
  border: var(--border-width) var(--border-style) transparent;
  color: var(--theme-text-secondary);
  padding: var(--spacing-xs) var(--spacing-sm);
  font-family: var(--font-family-icons);
  font-size: var(--font-size-lg);
  border-radius: var(--border-radius-base);
  cursor: pointer;
  transition: all var(--transition-duration-short);
}
.today-button {
  font-family: var(--font-family-base);
  font-size: var(--font-size-sm);
  margin-left: var(--spacing-base);
}
.nav-button:hover, .today-button:hover {
  background-color: var(--theme-bg-hover);
  color: var(--theme-text-primary);
  border-color: var(--theme-border-secondary);
}

.add-todo-for-date-section {
  display: flex;
  align-items: center;
  padding: var(--spacing-base);
  gap: var(--spacing-md);
  background: var(--theme-bg-secondary); /* Consistent distinct section bg */
  border-bottom: var(--border-width) var(--border-style) var(--theme-border-primary);
  flex-shrink: 0;
}

.todo-input-for-date {
  flex-grow: 1;
  padding: var(--spacing-sm) var(--spacing-md);
  background-color: var(--theme-bg-input);
  color: var(--theme-text-input);
  border: var(--border-width) var(--border-style) var(--theme-border-input);
  border-radius: var(--border-radius-base);
  font-size: var(--font-size-base);
}
.todo-input-for-date::placeholder {
  color: var(--theme-text-muted);
}
.todo-input-for-date:focus {
  border-color: var(--theme-accent-primary);
  box-shadow: 0 0 0 3px rgba(var(--theme-accent-primary-rgb), 0.3);
}

.add-button-for-date {
  padding: var(--spacing-sm) var(--spacing-lg);
  background: var(--theme-accent-gradient);
  color: var(--theme-text-on-accent);
  border: none;
  border-radius: var(--border-radius-base);
  font-size: var(--font-size-base);
  font-weight: var(--font-weight-medium);
  cursor: pointer;
  transition: filter var(--transition-duration-short), box-shadow var(--transition-duration-short);
  white-space: nowrap;
}
.add-button-for-date:hover {
  filter: brightness(1.1);
  box-shadow: 0 2px 8px rgba(var(--theme-accent-primary-rgb), 0.2);
}
.add-button-for-date:active {
  filter: brightness(0.95);
}

.calendar-main-area {
  display: flex;
  flex-grow: 1;
  overflow: hidden; /* Prevent layout issues */
}

.calendar-grid-container {
  flex: 0 0 65%; /* Adjust ratio as needed */
  display: flex;
  flex-direction: column;
  padding: var(--spacing-base);
  border-right: var(--border-width) var(--border-style) var(--theme-border-primary);
  background-color: var(--theme-bg-primary); /* Calendar grid background */
}

.calendar-weekdays {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  text-align: center;
  font-weight: var(--font-weight-medium);
  padding-bottom: var(--spacing-sm);
  border-bottom: var(--border-width) var(--border-style) var(--theme-border-secondary);
  margin-bottom: var(--spacing-xs);
  color: var(--theme-text-secondary);
}

.weekday {
  padding: var(--spacing-xs);
}

.calendar-days {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: var(--spacing-xxs); /* Minimal gap between day cells */
  flex-grow: 1;
}

.day-cell {
  border: var(--border-width) var(--border-style) var(--theme-border-secondary);
  padding: var(--spacing-xs);
  text-align: right;
  cursor: pointer;
  transition: background-color var(--transition-duration-short), border-color var(--transition-duration-short);
  position: relative;
  min-height: 70px; /* Adjust as needed for cell height */
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  background-color: var(--theme-bg-card); /* Default background for cells */
}
.day-cell:not(.blank):hover {
  background-color: var(--theme-bg-hover);
  border-color: var(--theme-border-primary);
}
.day-cell.blank {
  background-color: transparent;
  border-color: transparent;
  cursor: default;
}
.day-cell .day-number {
  font-size: var(--font-size-sm);
  color: var(--theme-text-secondary);
  align-self: flex-end;
}
.day-cell.today .day-number {
  color: var(--theme-accent-primary);
  font-weight: var(--font-weight-bold);
}
.day-cell.selected {
  background-color: var(--theme-calendar-selected-day-bg);
  color: var(--theme-calendar-selected-day-text);
  border: var(--border-width) var(--border-style) var(--theme-accent-primary);
  box-shadow: 0 0 8px rgba(var(--theme-accent-primary-rgb), 0.5);
  font-weight: var(--font-weight-bold);
}
.day-cell.selected .day-number {
  color: var(--theme-calendar-selected-day-text);
}
.day-cell.has-todos .todo-indicator {
  width: 6px;
  height: 6px;
  border-radius: var(--border-radius-circle);
  background-color: var(--theme-accent-secondary);
  align-self: flex-start;
  margin-top: var(--spacing-xxs);
}
.day-cell.selected.has-todos .todo-indicator {
  background-color: var(--theme-text-on-accent); /* Contrasting color on selected bg */
}

/* Right Panel: Selected Day Todos */
.selected-day-panel {
  flex: 1 1 35%; /* Adjust ratio as needed */
  padding: var(--spacing-base);
  display: flex;
  flex-direction: column;
  gap: var(--spacing-base);
  background-color: var(--theme-bg-secondary); /* Panel distinct background */
  overflow: hidden; /* Changed from overflow-y: auto */
}

.batch-controls-bar-calendar-panel {
  display: flex;
  align-items: center;
  padding: var(--spacing-sm) 0; /* No extra padding for this bar, aligns with list */
  gap: var(--spacing-md);
  border-bottom: var(--border-width) var(--border-style) var(--theme-border-primary);
  background-color: transparent; /* Inherits from panel or set to --theme-bg-tertiary */
  flex-shrink: 0;
}

/* Checkbox styles for calendar panel - ensure class names are unique */
.select-all-checkbox-calendar-panel,
.todo-select-checkbox-calendar-panel {
  appearance: none; -webkit-appearance: none; width: 18px; height: 18px;
  border: var(--border-width) var(--border-style) var(--theme-border-input);
  border-radius: var(--border-radius-sm); background-color: var(--theme-bg-input);
  cursor: pointer; position: relative; flex-shrink: 0;
  transition: background-color var(--transition-duration-short), border-color var(--transition-duration-short);
}
.select-all-checkbox-calendar-panel:checked,
.todo-select-checkbox-calendar-panel:checked {
  background: var(--theme-accent-primary); border-color: transparent;
}
.select-all-checkbox-calendar-panel:checked::after,
.todo-select-checkbox-calendar-panel:checked::after {
  content: ''; position: absolute; left: 6px; top: 3px; width: 5px; height: 10px;
  border: solid var(--theme-text-on-accent); border-width: 0 2px 2px 0; transform: rotate(45deg);
}
.select-all-checkbox-calendar-panel:focus,
.todo-select-checkbox-calendar-panel:focus {
  outline: none; box-shadow: 0 0 0 2px rgba(var(--theme-accent-primary-rgb), 0.3);
}

.select-all-label-calendar-panel {
  color: var(--theme-text-secondary);
  cursor: pointer;
  font-size: var(--font-size-sm);
  user-select: none;
}

/* Batch action buttons - reuse styles from HomeView or ensure consistency */
.batch-action-button {
  padding: var(--spacing-xs) var(--spacing-sm); font-size: var(--font-size-sm);
  color: var(--theme-text-secondary); background-color: var(--theme-bg-button-secondary);
  border: var(--border-width) var(--border-style) var(--theme-border-secondary);
  border-radius: var(--border-radius-base); cursor: pointer;
  transition: all var(--transition-duration-short); display: flex; align-items: center; gap: var(--spacing-xs);
}
.batch-action-button .button-icon {
  font-family: var(--font-family-icons); font-size: var(--font-size-base);
}
.batch-action-button:hover:not(:disabled) {
  background-color: var(--theme-bg-hover);
  color: var(--theme-text-primary);
  border-color: var(--theme-border-primary);
}
.batch-action-button:disabled {
  color: var(--theme-text-disabled);
  background-color: color-mix(in srgb, var(--theme-bg-button-secondary) 50%, transparent);
  border-color: var(--theme-border-primary);
  cursor: not-allowed;
}
.batch-action-button.delete:hover:not(:disabled) {
  background-color: var(--theme-button-danger-bg);
  color: var(--theme-text-on-accent);
  border-color: var(--theme-button-danger-bg-hover);
}
.batch-action-button.archive:hover:not(:disabled) {
  background-color: var(--theme-button-archive-bg);
  color: var(--theme-text-on-accent);
  border-color: var(--theme-button-archive-bg-hover);
}

.selected-day-todos-list {
  flex-grow: 1;
  overflow-y: auto; /* Added to make this part scrollable */
}

.todo-list {
  list-style: none;
  padding: 0;
  margin: 0;
  display: flex;
  flex-direction: column;
  gap: var(--spacing-sm);
}

.todo-item {
  display: flex;
  align-items: center;
  padding: var(--spacing-sm) var(--spacing-md);
  background-color: var(--theme-bg-card);
  border: var(--border-width) var(--border-style) var(--theme-border-primary);
  border-radius: var(--border-radius-base);
  transition: background-color var(--transition-duration-short), border-color var(--transition-duration-short);
  gap: var(--spacing-md);
}
.todo-item:hover {
  border-color: var(--theme-border-secondary);
  background-color: var(--theme-bg-hover);
}
.todo-item.selected-for-batch {
  background-color: color-mix(in srgb, var(--theme-accent-primary) 20%, var(--theme-bg-card));
  border-color: var(--theme-accent-primary);
}

.todo-status-icon {
  font-family: var(--font-family-icons);
  font-size: var(--font-size-lg);
  cursor: pointer;
  color: var(--theme-text-secondary);
  transition: color var(--transition-duration-short);
  padding: var(--spacing-xs);
  border-radius: var(--border-radius-circle);
  line-height: 1;
}
.todo-status-icon:hover {
  color: var(--theme-text-primary);
  background-color: var(--theme-bg-hover);
}
.todo-status-icon.completed-icon {
  color: var(--theme-accent-primary);
}
.todo-status-icon.completed-icon:hover {
  color: var(--theme-accent-highlight);
}

.priority-indicator {
  width: 10px;
  height: 10px;
  border-radius: var(--border-radius-circle);
  flex-shrink: 0;
}

.todo-label {
  flex-grow: 1;
  color: var(--theme-text-primary);
  cursor: text;
  user-select: text;
  padding: var(--spacing-xs) 0;
  line-height: var(--line-height-base);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  min-width: 0;
}
.todo-item.completed .todo-label {
  color: var(--theme-text-muted);
  text-decoration: line-through;
  text-decoration-color: var(--theme-text-disabled);
}

.todo-edit-input {
  flex-grow: 1;
  padding: var(--spacing-xs) var(--spacing-sm);
  background-color: var(--theme-bg-input);
  color: var(--theme-text-input);
  border: var(--border-width) var(--border-style) var(--theme-border-input);
  border-radius: var(--border-radius-base);
  font-size: var(--font-size-base);
  line-height: var(--line-height-base);
  min-width: 0;
}
.todo-edit-input:focus {
  border-color: var(--theme-accent-primary);
  box-shadow: 0 0 0 3px rgba(var(--theme-accent-primary-rgb), 0.3);
}

.empty-selected-day-message {
  text-align: center;
  padding: var(--spacing-xl) var(--spacing-base);
  color: var(--theme-text-muted);
  font-style: italic;
  margin-top: var(--spacing-lg);
  flex-grow: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.calendar-footer {
  padding: var(--spacing-sm) var(--spacing-base);
  border-top: var(--border-width) var(--border-style) var(--theme-border-primary);
  background-color: var(--theme-bg-secondary);
  flex-shrink: 0;
}

.priority-legend-container {
  padding: 0;
  background-color: transparent;
}
.priority-legend {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: var(--spacing-md);
}
.legend-item {
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
  font-size: var(--font-size-sm);
  color: var(--theme-text-muted);
}
.legend-dot {
  width: 10px;
  height: 10px;
  border-radius: var(--border-radius-circle);
}

/* Context Menu & Submenu Styles (re-use from HomeView if identical) */
.context-menu,
.priority-submenu {
  position: fixed;
  z-index: 1000;
  background-color: var(--theme-bg-tertiary);
  border: var(--border-width) var(--border-style) var(--theme-border-secondary);
  border-radius: var(--border-radius-base);
  box-shadow: var(--theme-shadow-popover);
  padding: var(--spacing-xs) 0;
}
.priority-submenu { z-index: 1001; min-width: 100px; }
.context-menu { min-width: 160px; }

.context-menu-item {
  display: flex; align-items: center; gap: var(--spacing-sm);
  padding: var(--spacing-xs) var(--spacing-sm);
  color: var(--theme-text-secondary);
  cursor: pointer; font-size: var(--font-size-sm);
  border: none; background-color: transparent;
  width: 100%; text-align: left;
  transition: background-color var(--transition-duration-short), color var(--transition-duration-short);
}
.context-menu-item:hover {
  background-color: var(--theme-bg-hover);
  color: var(--theme-text-primary);
}
.context-menu-item .priority-dot {
  width: 10px; height: 10px;
  border-radius: var(--border-radius-circle);
  flex-shrink: 0;
}
.priority-submenu-container { position: relative; }
.submenu-arrow {
  font-family: var(--font-family-icons);
  margin-left: auto;
  font-size: calc(var(--font-size-sm) * 0.9);
}
</style> 